<template>
  <!-- 家长查看学生作业列表 -->
  <div class="par-joblist swipe-wrapper">
    <h1 class="title">学情报告--作业列表</h1>
    <!-- 家长绑定了多个学生时显示所有学生的下拉选择框 -->
    <cube-select
      v-if="options.length>1"
      v-model="value"
      :title="title"
      :options="options"
      :placeholder="placeholder"
      :auto-pop="autoPop"
      :disabled="disabled"
      @change="change"
    ></cube-select>
    <!-- 家长绑定一个学生时显示该学生的姓名 -->
    <h5 class="className" v-if="options.length===1">{{options[0].text}}</h5>
    <cube-tab-bar
      v-model="selectedLabel"
      show-slider
      :use-transition="disabled"
      ref="tabNav"
      :data="tabLabels"
    ></cube-tab-bar>
    <div class="tab-slide-container">
      <cube-slide
        ref="slide"
        :loop="loop"
        :initial-index="initialIndex"
        :auto-play="autoPlay"
        :show-dots="showDots"
        :options="slideOptions"
        @scroll="scroll"
        @change="changePage"
      >
        <!-- 学生未完成 -->
        <cube-slide-item>
          <cube-scroll v-if="undoData.length>0" :data="undoData" :options="scrollOptions">
            <ul class="list-wrapper">
              <li class="tab-panel-li" v-for="(hero, index) in undoData" :key="index">
                <div @click="onItemClick(hero, index)" class="item-inner">
                  <div class="text">
                    <p class="item-time">阅读书籍:&nbsp;{{hero.book_name}}</p>
                    <p class="item-time">阅读内容:&nbsp;{{hero.pagenums}}</p>
                    <p class="item-time">截止日期:&nbsp;{{hero.end_time|formatDate}}</p>
                    <!-- <p class="item-time">老师姓名:&nbsp;{{hero.teacherName}}</p> -->
                  </div>
                  <div class="icon">
                    <p class="item-status item-undo">未完成</p>
                  </div>
                </div>
              </li>
            </ul>
          </cube-scroll>
          <div v-else class="tips">
            <div class="tips-icon">
              <i class="cubeic-alert"></i>
            </div>
            <h3>暂无学生未完成作业</h3>
          </div>
        </cube-slide-item>
        <!-- 家长未签名 -->
        <cube-slide-item>
          <cube-scroll v-if="unsignedData.length>0" :data="unsignedData" :options="scrollOptions">
            <ul class="list-wrapper">
              <li class="tab-panel-li" v-for="(hero, index) in unsignedData" :key="index">
                <div @click="onItemClick(hero, index)" class="item-inner">
                  <div class="text">
                    <p class="item-time">阅读书籍:&nbsp;{{hero.book_name}}</p>
                    <p class="item-time">阅读内容:&nbsp;{{hero.pagenums}}</p>
                    <p class="item-time">完成日期:&nbsp;{{hero.updateTime|formatDate}}</p>
                    <!-- <p class="item-time">老师姓名:&nbsp;{{hero.teacherName}}</p> -->
                  </div>
                  <div class="icon">
                    <p class="item-status item-puneva">未签名</p>
                  </div>
                </div>
              </li>
            </ul>
          </cube-scroll>
          <div v-else class="tips">
            <div class="tips-icon">
              <i class="cubeic-alert"></i>
            </div>
            <h3>暂无未签名作业</h3>
          </div>
        </cube-slide-item>
        <!-- 家长已签名 -->
        <cube-slide-item>
          <cube-scroll v-if="signedData.length>0" :data="signedData" :options="scrollOptions">
            <ul class="list-wrapper">
              <li class="tab-panel-li" v-for="(hero, index) in signedData" :key="index">
                <div @click="onItemClick(hero, index)" class="item-inner">
                  <div class="text">
                    <p class="item-time">阅读书籍:&nbsp;{{hero.book_name}}</p>
                    <p class="item-time">阅读内容:&nbsp;{{hero.pagenums}}</p>
                    <p class="item-time">完成日期:&nbsp;{{hero.updateTime|formatDate}}</p>
                    <!-- <p class="item-time">老师姓名:&nbsp;{{hero.teacherName}}</p> -->
                  </div>
                  <div class="icon">
                    <p class="item-status item-alldone">已签名</p>
                    <img v-if="hero.parentEvaluate=='0'" class="cubeic-icon" :src="images[0].src">
                    <img v-if="hero.parentEvaluate=='1'" class="cubeic-icon" :src="images[1].src">
                    <img v-if="hero.parentEvaluate=='2'" class="cubeic-icon" :src="images[2].src">
                  </div>
                </div>
              </li>
            </ul>
          </cube-scroll>
          <div v-else class="tips">
            <div class="tips-icon">
              <i class="cubeic-alert"></i>
            </div>
            <h3>暂无已签名作业</h3>
          </div>
        </cube-slide-item>
      </cube-slide>
    </div>
  </div>
</template>

<script>
import { formatDate } from "@/assets/js/date.js";
export default {
  name: "ParJobList",
  data() {
    return {
      options: [],
      currentStudentID: "",
      value: "",
      title: "学生",
      placeholder: "请选择学生",
      autoPop: false,
      selectedLabel: "未签名",
      disabled: false,
      images: [
        {
          src: require("../../assets/img/0.png")
        },
        { src: require("../../assets/img/1.png") },
        { src: require("../../assets/img/2.png") }
      ],
      tabLabels: [
        {
          label: "未完成",
          status: "0"
        },
        {
          label: "未签名",
          status: "1"
        },
        {
          label: "已签名",
          status: "2"
        }
      ],
      loop: false,
      autoPlay: false,
      showDots: false,
      slideOptions: {
        listenScroll: true,
        probeType: 3,
        /* lock y-direction when scrolling horizontally and  vertically at the same time */
        directionLockThreshold: 0
      },
      scrollOptions: {
        /* lock x-direction when scrolling horizontally and  vertically at the same time */
        directionLockThreshold: 0
      },
      undoData: [],
      unsignedData: [],
      signedData: []
    };
  },
  filters: {
    formatDate(time) {
      let date = new Date(time);
      return formatDate(date, "yyyy-MM-dd hh:mm:ss");
    }
  },
  computed: {
    initialIndex() {
      let index = 0;
      index = this.findIndex(
        this.tabLabels,
        item => item.label === this.selectedLabel
      );
      return index;
    }
  },
  created() {
    if (localStorage.getItem("openID")) {
      this.getStudents();
    } else {
      this.getCode();
    }
  },
  mounted() {},
  methods: {
    getUrlKey(name) {
      //获取url 参数
      return (
        decodeURIComponent(
          (new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
            location.href
          ) || [, ""])[1].replace(/\+/g, "%20")
        ) || null
      );
    },
    getCode() {
      // 非静默授权，第一次有弹框
      const code = this.getUrlKey("code"); // 截取路径中的code，如果没有就去微信授权，如果已经获取到了就直接传code给后台获取openId
      const local = window.location.href;
      const appid = "wx6d7dcd07ca4fa211";
      if (code == null || code === "") {
        window.location.href =
          "http://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
          appid +
          "&redirect_uri=" +
          encodeURIComponent(local) +
          "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
      } else {
        this.getOpenId(code); //把code传给后台获取用户信息
      }
    },
    getOpenId(code) {
      // 通过code获取 openId等用户信息，/oauth2/printOpenID 为后台接口
      this.$http
        .post("/oauth2/printOpenID", { code: code })
        .then(res => {
          let openID = res.data;
          this.$store.state.openID = openID;
          localStorage.setItem("openID", openID);
          // 获取学生姓名(列表)和家长未批阅作业列表
          this.getStudents();
        })
        .catch(error => {
          console.log(error);
        });
    },

    async getStudents() {
      let requestData = {
        openId: localStorage.getItem("openID")
      };
      await this.$http
        .post("/api000032", requestData)
        .then(response => {
          // 如果通过openid获取不到学生信息，跳转到添加学生页面
          if (response.data === "") {
            this.$createToast({
              type: "loading",
              time: 2000,
              txt: "您未绑定学生，即将跳转到绑定学生页面",
              onTimeout: () => {
                this.$router.push({ path: "/paradd" });
              }
            }).show();
          } else {
            this.options = response.data.map(item => {
              return { value: item.id, text: item.name };
            });
            // 设置选中项的value
            if (this.options.length >= 1) {
              // 设置选择器被选中的项
              this.value = this.options[0].text;
            }

            this.currentStudentID = this.options[0].value;
            // 获取未签名作业列表
            this.changePage(1, this.currentStudentID);
          }
        })
        .catch(function(error) {
          this.$createToast({
            type: "warn",
            time: 1000,
            txt: error
          }).show();
        });
    },
    // 根据状态和学生id，获取学生作业列表
    getStudentJobs(url, data) {
      this.$http
        .post(url, data)
        .then(response => {
          if (data.status == "0") {
            this.undoData = response.data; //未完成
          } else if (data.status == "1") {
            this.unsignedData = response.data; // 未签名
          } else {
            this.signedData = response.data; //已签名
          }
        })
        .catch(function(error) {
          this.$createToast({
            type: "warn",
            time: 1000,
            txt: error
          }).show();
        });
    },
    findIndex(ary, fn) {
      if (ary.findIndex) {
        return ary.findIndex(fn);
      }
      /* istanbul ignore next */
      let index = -1;
      /* istanbul ignore next */
      ary.some(function(item, i, ary) {
        const ret = fn.call(this, item, i, ary);
        if (ret) {
          index = i;
          return ret;
        }
      });
      /* istanbul ignore next */
      return index;
    },
    change(value, index, text) {
      // 切换学生
      this.currentStudentID = this.options[index].value;
      this.value = text;
      for (let i = 0; i < 3; i++) {
        this.changePage(i, this.currentGradeID);
      }
    },
    onItemClick(item) {
      this.$store.state.homeworkId = item.homework_id;
      this.$store.state.studentId = this.currentStudentID;
      this.$router.push({
        path: "/parentsjob",
        query: item
      });
    },
    changePage(current) {
      this.selectedLabel = this.tabLabels[current].label;
      let requetData = {
        openId: localStorage.getItem("openID"),
        studentId: this.currentStudentID,
        status: this.tabLabels[current].status
      };
      this.getStudentJobs("/api000034", requetData);
    },
    scroll(pos) {
      const x = Math.abs(pos.x);
      const tabItemWidth = this.$refs.tabNav.$el.clientWidth;
      const slideScrollerWidth = this.$refs.slide.slide.scrollerWidth;
      const deltaX = (x / slideScrollerWidth) * tabItemWidth;
      this.$refs.tabNav.setSliderTransform(deltaX);
    }
  }
};
</script>

<style lang="scss">
.par-joblist {
  .title {
    font-size: 16px;
    font-weight: 700;
    padding-left: 20px;
    height: 50px;
    line-height: 50px;
    border-left: 5px solid #fc9153;
    background: #fee9dd;
  }
  .className {
    color: #fc9153;
    font-size: 20px;
    font-weight: 700;
    text-align: center;
    margin: 15px;
  }
  // 设置tab的样式
  .cube-tab div {
    font-size: 16px;
    font-weight: 700;
  }
  .cube-select {
    margin: 15px auto;
    width: fit-content;
    padding: 5px 20px;
    .cube-select-text {
      letter-spacing: 10px;
      font-size: 20px;
      font-weight: 700;
      color: #fc9153;
    }
  }
  /* 设置列表样式 */
  .item-inner {
    display: flex;
    justify-content: space-between;
    font-size: 12px;
    margin: 20px;
    padding-bottom: 20px;
    height: 60px;
    border-bottom: 5px solid rgb(233, 233, 233);
    /* 老师作业列表或学生作业列表每个作业信息框的样式 */
    .text {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }
    /* 老师作业列表或学生作业列表每个作业信息框右侧状态或图标样式 */
    .icon {
      align-self: center;
      display: flex;
      flex-direction: column;
      align-items: center;
      .item-status {
        padding: 5px 10px;
      }
      /* /已完成字体样式 */
      .item-alldone {
        color: black;
        text-align: right;
      }
      /* 设置家长心情图片宽度 */
      .cubeic-icon {
        width: 30px;
      }
      /* // 学生未完成 */
      .item-undo {
        color: red;
      }
      /* 家长未评价 */
      .item-puneva {
        color: rgb(189, 58, 58);
      }
    }
  }
  .tips {
    margin-top: 40%;
    text-align: center;
    font-size: 16px;
    color: #fc9153;
    .tips-icon {
      margin-bottom: 20px;
      i {
        color: #fc9153;
        font-size: 50px;
      }
    }
  }
}
</style>